//
//  InformationViewController.m
//  DianNaoWang
//
//  Created by dllo on 15/11/2.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "InformationViewController.h"
#import "FitHeader.h"
#import "CFNetworkFromAFNetworking.h"
#import "ChannelNum.h"
#import "ChanelNumCell.h"
#import "PageCollectionViewCell.h"
#import "TuShangCollectionViewCell.h"
#import "CFWebViewController.h"
#import "SearchBarViewController.h"
#import "DataBaseManager.h"
#import "ImageInfoViewController.h"
#import "FavoriteWapPage.h"
#import "LabelCell.h"
@interface InformationViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,pageCollectionViewCellDelegate,TuShangCollectionViewCellDelegate>
@property(nonatomic, retain)UICollectionView *pageCollectionView;
@property(nonatomic, retain)UICollectionView *channelCollectionView;
@property(nonatomic, retain)NSMutableArray *channelDataSourceArray;
@property(nonatomic, retain)UIView *viewBar;
@property(nonatomic, retain)NSTimer *timer;

@property(nonatomic, retain)NSMutableArray *totleArray;
@property(nonatomic, retain)NSMutableArray *otherArray;

@property(nonatomic, retain)UICollectionView *addCollectionView;
@property(nonatomic, retain)UICollectionView *deleteCollection;
@property(nonatomic, retain)UIView *backView;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, retain)UILabel *labelT;
@property(nonatomic, retain)UILabel *labelF;
@property(nonatomic, retain)UIView *grayerView;
@end

@implementation InformationViewController

-(void)viewWillAppear:(BOOL)animated
{
    [_pageCollectionView reloadData];
    _flag = 0;
}

- (void)getTotleArray
{
#pragma mark 首次进入 分配频道 记录首次登入
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"firstTime"]) {
        [CFNetworkFromAFNetworking askObjectByURLString:@"http://lib.wap.zol.com.cn/ipj/classList/?v=3.0&vs=and400" BodyString:nil WithObjectBlock:^(id object) {
            NSArray *array  = object;
            for (NSDictionary *dic in array) {
                //去掉"订阅频道"和"聚合"
                if (![[dic objectForKey:@"name"] isEqualToString:@"订阅"] && ![[dic objectForKey:@"name"] isEqualToString:@"聚合"] && ![[dic objectForKey:@"name"] isEqualToString:@"行情"]) {
                    ChannelNum *channelNum = [[ChannelNum alloc]init];
                    [channelNum setValuesForKeysWithDictionary:dic];
                    [self.totleArray addObject:channelNum];
                }
            }
            //如果数据请求回来了就本地存储
            if (self.totleArray) {
                self.channelDataSourceArray = [NSMutableArray array];
                self.otherArray =  [NSMutableArray array];
                for (NSInteger i = 0; i < _totleArray.count; i++) {
                    if (i < _totleArray.count / 2) {
                        [DataBaseManager creatChannelTable];
                        [DataBaseManager insertChannel:_totleArray[i]];
                    }else{
                        
                        [DataBaseManager creatDChannelTable];
                        [DataBaseManager insertDChannel:_totleArray[i]];
                    }
                }
                [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstTime"];
//                
//        else{
//            self.channelDataSourceArray = [DataBaseManager selectChannel];
//            if (self.channelDataSourceArray.count == 0) {
//                [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"firstTime"];
//            }
//        }
//[[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"firstTime"];
                self.otherArray = [DataBaseManager selectDChannel];
                self.channelDataSourceArray = [DataBaseManager selectChannel];
                [_addCollectionView reloadData];
                [_deleteCollection reloadData];
                [_pageCollectionView reloadData];
                [_channelCollectionView reloadData];
                
            }
        }];
    }else{
        self.otherArray = [DataBaseManager selectDChannel];
        self.channelDataSourceArray = [DataBaseManager selectChannel];
        [_addCollectionView reloadData];
        [_deleteCollection reloadData];
        [_pageCollectionView reloadData];
        [_channelCollectionView reloadData];
    }
}

-(void)loadView
{
    [super loadView];
#pragma mark 获取数据
    self.view.backgroundColor = BackgroundColor;
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.totleArray = [NSMutableArray array];
    [self getTotleArray];
    
    UIBarButtonItem *channelPageItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"5@2x"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(channelPageItemAction)];
    UIBarButtonItem *searchItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"6@2x"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(searchItemAction)];
    //两个按钮的方法在最下方
    self.navigationItem.rightBarButtonItems = @[searchItem, channelPageItem];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;//创建时布局
    //顶部频道collectionView
    UICollectionViewFlowLayout *flowLayout1 = [[UICollectionViewFlowLayout alloc]init];
    flowLayout1.itemSize = CGSizeMake(50, 20 * FitHeight);
    flowLayout1.minimumLineSpacing = 30;
    flowLayout1.minimumInteritemSpacing = 0;
    flowLayout1.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout1.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _channelCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(10 *FitWidth, 0, 260 * FitWidth, 30 * FitHeight) collectionViewLayout:flowLayout1];
    _channelCollectionView.backgroundColor = NavigationBarBackgroundColor;
    _channelCollectionView.delegate = self;
    _channelCollectionView.dataSource = self;
    
#pragma mark 提醒条
    _viewBar = [[UIView alloc]initWithFrame:CGRectMake(5, 28 * FitHeight, 40 * FitWidth, 2 * FitHeight)];
    _viewBar.backgroundColor = [UIColor whiteColor];
    _viewBar.layer.cornerRadius = 1.5;
    [_channelCollectionView addSubview:_viewBar];

    
    self.navigationItem.titleView = _channelCollectionView;
    _channelCollectionView.showsHorizontalScrollIndicator = false;
    [_channelCollectionView registerClass:[ChanelNumCell class] forCellWithReuseIdentifier:@"identifier"];
    
    //页面collectionView
    UICollectionViewFlowLayout *flowLayout2 = [[UICollectionViewFlowLayout alloc]init];
    flowLayout2.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - (64 + 49) * FitHeight);
    flowLayout2.minimumInteritemSpacing = 0;
    flowLayout2.minimumLineSpacing = 0;
    flowLayout2.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout2.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _pageCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64 * FitHeight - 49 * FitHeight) collectionViewLayout:flowLayout2];//注意:创建时 高度不要减tabBar的高度,否则影响collectionview的位置,但如果加了self.automaticallyAdjustsScrollViewInsets = NO;语句就可以了.item和item里的内容该多大还多大
    
    //_pageCollectionView.backgroundColor = [UIColor blackColor];
    _pageCollectionView.backgroundColor = BackgroundColor;
    _pageCollectionView.delegate = self;
    _pageCollectionView.dataSource = self;
    _pageCollectionView.pagingEnabled = YES;
    _pageCollectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_pageCollectionView];

    
    [_pageCollectionView registerClass:[PageCollectionViewCell class] forCellWithReuseIdentifier:@"pageIdentifier"];
    [_pageCollectionView registerClass:[TuShangCollectionViewCell class] forCellWithReuseIdentifier:@"tushangIdentifier"];
    
    
#pragma mark - 制作选频道的下拉页面
    _backView  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
    _backView.backgroundColor = BackgroundColor;
    
    UICollectionViewFlowLayout *flolayoutDelete = [[UICollectionViewFlowLayout alloc]init];
    flolayoutDelete.itemSize = CGSizeMake(60, 20);
    flolayoutDelete.minimumLineSpacing = 20;
    flolayoutDelete.minimumInteritemSpacing = 11;
    flolayoutDelete.sectionInset = UIEdgeInsetsMake(20, 11, 20, 11);
    
    UICollectionViewFlowLayout *flowLayourAdd = [[UICollectionViewFlowLayout alloc]init];
    flowLayourAdd.itemSize = CGSizeMake(60, 20);
    flowLayourAdd.minimumLineSpacing = 20;
    flowLayourAdd.minimumInteritemSpacing = 11;
    flowLayourAdd.sectionInset = UIEdgeInsetsMake(20, 11, 20, 11);
    
    
    _addCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0) collectionViewLayout:flowLayourAdd];
    _addCollectionView.delegate = self;
    _addCollectionView.dataSource = self;
    _addCollectionView.backgroundColor = BackgroundColor;
    [_backView addSubview:_addCollectionView];
    
    _deleteCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(_addCollectionView.frame.origin.x, _addCollectionView.frame.origin.y + _addCollectionView.frame.size.height + 20, _addCollectionView.frame.size.width, 0) collectionViewLayout:flolayoutDelete];
    _deleteCollection.backgroundColor = BackgroundColor;
    _deleteCollection.delegate = self;
    _deleteCollection.dataSource = self;
    _deleteCollection.showsHorizontalScrollIndicator = NO;
    _deleteCollection.showsVerticalScrollIndicator = NO;
    [_backView addSubview:_deleteCollection];
    
    
    
    [_addCollectionView registerClass:[LabelCell class] forCellWithReuseIdentifier:@"cell1"];
    [_addCollectionView registerClass:[LabelCell class] forCellWithReuseIdentifier:@"cell"];
    [_deleteCollection registerClass:[LabelCell class] forCellWithReuseIdentifier:@"cell2"];
    
    //顶部label
    _labelT = [[UILabel alloc]initWithFrame:CGRectMake(11, 10, ScreenWidth, 0)];
    _labelT.text = @"现有栏目,点击删除频道";
    _labelT.backgroundColor = otherTextColor;
    _labelT.font = [UIFont systemFontOfSize:13];
    [_backView addSubview:_labelT];

    
    _labelF = [[UILabel alloc]initWithFrame:CGRectMake(_labelT.frame.origin.x, _addCollectionView.frame.origin.y + _addCollectionView.frame.size.height, _labelT.frame.size.width, _labelT.frame.size.height)];
    _labelF.text = @"更多栏目,点击添加频道";
    _labelF.backgroundColor = otherTextColor;
    _labelF.font = [UIFont systemFontOfSize:13];
    [_backView addSubview:_labelF];
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
    
    [self.view addSubview:_backView];

    
    //页面遮挡
    _grayerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0)];
    _grayerView.backgroundColor = [UIColor colorWithRed:.85 green:.85 blue:.85 alpha:.5];
    UITapGestureRecognizer *tapTodismiss = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapTodismisAction)];
    [_grayerView addGestureRecognizer:tapTodismiss];

    [self.view addSubview:_grayerView];

    
    //夜间模式的监听者
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(colorChange) name:@"colorChange" object:nil];
}
#pragma mark - 夜间模式 监听到变化后采取的措施
- (void )colorChange
{
    self.view.backgroundColor = BackgroundColor;
    _pageCollectionView.backgroundColor = BackgroundColor;
}


//collectionView个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == _addCollectionView) {
        return _channelDataSourceArray.count;
    }
    if (collectionView == _deleteCollection) {
        return _otherArray.count;
    }
    if (collectionView == _channelCollectionView) {
        return self.channelDataSourceArray.count;
    }
    if (collectionView == _pageCollectionView) {
        return self.channelDataSourceArray.count;
    }
    return 0;
}
//collectionView样式
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _addCollectionView) {
        if (indexPath.row == 0) {
            LabelCell *addcell1 = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
            addcell1.nameLabel.text = [_channelDataSourceArray[indexPath.row] name];
            addcell1.nameLabel.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
            return addcell1;
        }
        LabelCell *addCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell1" forIndexPath:indexPath];
        addCell.nameLabel.text = [_channelDataSourceArray[indexPath.row] name];
        return addCell;
    }
    if (collectionView == _deleteCollection) {
        LabelCell *deCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell2" forIndexPath:indexPath];
        deCell.nameLabel.text = [_otherArray[indexPath.row] name];
        return deCell;
    }
    if (collectionView == _channelCollectionView) {
        ChanelNumCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
        cell.chanelNum = self.channelDataSourceArray[indexPath.row];
        return cell;
    }
    if (collectionView == _pageCollectionView) {
        
#pragma mark 这里判断channel.Id是不是3,如果是就用图赏的cell,如果是5就用行情的cell
        if ([[_channelDataSourceArray[indexPath.row] Id] isEqualToString:@"3"]) {
            TuShangCollectionViewCell *cell3 = [collectionView dequeueReusableCellWithReuseIdentifier:@"tushangIdentifier" forIndexPath:indexPath];
            [cell3.tableView reloadData];
            cell3.tableView.backgroundColor = BackgroundColor;
            cell3.delegate = self;
            return cell3;
        }
        //        else if ([[_channelDataSourceArray[indexPath.row] Id] isEqualToString:@"5"]){
        //            这里写行情的cell;
        //        }
        else{
            PageCollectionViewCell *cell2 = [collectionView dequeueReusableCellWithReuseIdentifier:@"pageIdentifier" forIndexPath:indexPath];
            //[cell2.timer setFireDate:[NSDate distantFuture]];
            cell2.channel = self.channelDataSourceArray[indexPath.row];
            cell2.delegate = self;
            return cell2;
        }
    }
    return nil;
}

#pragma mark 实现pageCollectionViewCell的代理方法,传值并push到详情页
-(void)paseValueAndPush:(NSString *)Id Title:(NSString *)title
{
    CFWebViewController *cfwebVC = [[CFWebViewController alloc]init];
    NSString *urlString = [NSString stringWithFormat:@"http://lib.wap.zol.com.cn/ipj/clientArticle/?v=3.1&fontSize=middle&id=%@&picHeight=2000&picOpen=1&picWidth=500&tag=0&vs=iph430", Id];
    FavoriteWapPage *FWP = [[FavoriteWapPage alloc]init];
    FWP.wapUrlString = urlString;
    FWP.title = title;
    cfwebVC.favorWap = FWP;
    
    [self.navigationController pushViewController:cfwebVC animated:YES];
}


#pragma mark - 点击事件 数据库存车 同步页面和标题
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _channelCollectionView) {
        _viewBar.frame = CGRectMake(indexPath.row * 80 + 5, 28 * FitHeight, 40 * FitWidth, 2 * FitHeight);
        _pageCollectionView.contentOffset = CGPointMake(indexPath.row * ScreenWidth, 0);
    }
    //点击添加 删除label
    if (collectionView == _addCollectionView) {
        if (indexPath.row != 0) {
            ChannelNum *cN = _channelDataSourceArray[indexPath.row];
            [DataBaseManager insertDChannel:cN];
            self.otherArray = [DataBaseManager selectDChannel];
            [DataBaseManager deleteChannel:cN];
            self.channelDataSourceArray = [DataBaseManager selectChannel];
            ////NSLog(@"%@", cN.name);
            
            [_channelCollectionView reloadData];
            [_pageCollectionView reloadData];
            [_addCollectionView reloadData];
            [_deleteCollection reloadData];
        }
        
    }
    if (collectionView == _deleteCollection) {
        ChannelNum *cN = _otherArray[indexPath.row];
        [DataBaseManager insertChannel:cN];
        self.channelDataSourceArray = [DataBaseManager selectChannel];
        [DataBaseManager deleteDChannel:cN];
        self.otherArray = [DataBaseManager selectDChannel];
        ////NSLog(@"%@", cN.name);
        
        [_channelCollectionView reloadData];
        [_pageCollectionView reloadData];
        [_addCollectionView reloadData];
        [_deleteCollection reloadData];
    }
}



-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _pageCollectionView) {
        CGPoint point = _pageCollectionView.contentOffset;
        if (point.x / ScreenWidth < 5) {
            _channelCollectionView.contentOffset = CGPointMake(point.x * 50 / ScreenWidth, 0);
        }
        if (point.x / ScreenWidth >= 5 && point.x / ScreenWidth < _channelDataSourceArray.count - 1) {
            _channelCollectionView.contentOffset = CGPointMake(point.x * 80 / ScreenWidth - 130, 0);
        }
        if (point.x / ScreenWidth >= _channelDataSourceArray.count - 1) {
            _channelCollectionView.contentOffset = CGPointMake(point.x * 80 / ScreenWidth - 160, 0);
        }
        _viewBar.frame = CGRectMake(point.x * 80 / ScreenWidth + 5, 28 * FitHeight, 40 * FitWidth, 2 * FitHeight);
    }
}


#pragma mark 执行图赏页点击方法的代理方法
-(void)pushAndPassId:(NSString *)tushangId
{
    ImageInfoViewController *IIvc = [[ImageInfoViewController alloc]init];
    IIvc.Id = tushangId;
    [self.navigationController pushViewController:IIvc animated:NO];
}


#pragma mark tap 事件
- (void)tapTodismisAction
{
    [UIView animateWithDuration:.2 animations:^{
        _backView.frame = CGRectMake(0, 0, ScreenWidth, 0);
        _addCollectionView.frame = CGRectMake(0, 0, ScreenWidth, 0);
        _deleteCollection.frame = CGRectMake(0, 0, ScreenWidth, 0);
        _labelF.frame = CGRectMake(0, 0, ScreenWidth, 0);
        _labelT.frame = CGRectMake(0, 0, ScreenWidth, 0);
        _flag = 0;
        _grayerView.frame = CGRectMake(0, 0, ScreenWidth, 0);
    }];
}

#pragma mark item的点击方法
- (void)channelPageItemAction
{
    if (_flag) {
        [UIView animateWithDuration:.2 animations:^{
            _backView.frame = CGRectMake(0, 0, ScreenWidth, 0);
            _addCollectionView.frame = CGRectMake(0, 0, ScreenWidth, 0);
            _deleteCollection.frame = CGRectMake(0, 0, ScreenWidth, 0);
            _labelF.frame = CGRectMake(0, 0, ScreenWidth, 0);
            _labelT.frame = CGRectMake(0, 0, ScreenWidth, 0);
            _grayerView.frame = CGRectMake(0, 0, ScreenWidth, 0);
            _flag = 0;
        }];
        
    }else{
        [UIView animateWithDuration:.3 animations:^{
            _backView.frame = CGRectMake(0, 0, ScreenWidth, 370);
            _addCollectionView.frame = CGRectMake(0, 40, ScreenWidth, 150);
            _deleteCollection.frame = CGRectMake(_addCollectionView.frame.origin.x, _addCollectionView.frame.origin.y + _addCollectionView.frame.size.height + 20, _addCollectionView.frame.size.width, 150);
            _labelT.frame = CGRectMake(0, 10, ScreenWidth, 20);
            _labelF.frame = CGRectMake(_labelT.frame.origin.x, _addCollectionView.frame.origin.y + _addCollectionView.frame.size.height, _labelT.frame.size.width, _labelT.frame.size.height);
            _flag = 1;
            _grayerView.frame = CGRectMake(_backView.frame.origin.x, _backView.frame.origin.y + _backView.frame.size.height, ScreenWidth, ScreenHeight - _backView.frame.size.height);
        }];
    }
    
}

- (void)searchItemAction
{
    SearchBarViewController *sBVC = [[SearchBarViewController alloc]init];
    sBVC.keyID = 1;
    sBVC.modalTransitionStyle = 2;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:sBVC];
    [self presentViewController:nav animated:YES completion:NULL];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
